package com.ztao.service.impl;
import com.alibaba.fastjson.JSON;
import com.heima.model.common.apArticle.dto.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.mess.UpdateArticleMess;
import com.heima.model.common.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import com.ztao.common.constants.BehaviorConstants;
import com.ztao.common.constants.HotArticleConstants;
import com.ztao.redis.CacheService;
import com.ztao.service.ApCollectionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class ApCollectionServiceImpl implements ApCollectionService {
 
    @Resource
    private CacheService cacheService;
    @Resource
    private KafkaTemplate kafkaTemplate;
 
    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        // 1. 检查参数
        if(dto.getEntryId() == null || dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
 
        // 2. 判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setArticleId(dto.getEntryId());
        mess.setType(UpdateArticleMess.UpdateArticleType.COLLECTION);
        // 3. 查询收藏记录
        String collectionJson = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(), dto.getEntryId().toString());
        if(StringUtils.isNotBlank(collectionJson) && dto.getOperation() == 0) {
            // 已收藏
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已收藏");
        }
 
        // 4. 收藏
        if(dto.getOperation() == 0) {
            log.info("文章收藏，保存key: {}, {}, {}", dto.getEntryId(), user.getId().toString(), JSON.toJSONString(dto));
            cacheService.hPut(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(), dto.getEntryId().toString(), JSON.toJSONString(dto));
            mess.setAdd(1);
        } else {
            // 取消收藏
            log.info("文章收藏，删除key: {}, {}, {}", dto.getEntryId().toString(), user.getId().toString(), JSON.toJSONString(dto));
            cacheService.hDelete(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(), dto.getEntryId().toString());
            mess.setAdd(-1);
        }
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC,JSON.toJSONString(mess));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}